<?php

namespace Chealth\Controller;

use Think\Controller;
use User\Model\UcenterMemberModel;

class ApiController extends Controller{
	private $user;
	private $uid;
    private $allow_edit_info;

    public function _initialize(){
        if (!in_array(ACTION_NAME, array('notice'))) {
            if ($this->is_login() != true) {
                $this->error('请登录', 'login');
            }
        }
        if (!in_array(ACTION_NAME, array('getemail', 'notice'))){
            $this->defaultUser();   
        }
        define('NOW_TIME_FORMAT', strtotime(date('Y-m-d')));
        $this->status_maps = C('FRONT_HEALTH_ENTER_STATUS');
    }

    /**
     * 首页, 体检列表
     * @param int $page
     * @param int $r
     */
    public function  index($page = 1, $r = 50){
        //查找所有预约项目
        $ChealthTimeModel = D('Chealth/ChealthTime');

        list($list,$totalCount) = $ChealthTimeModel->getListByPage('' ,$page, 'id DESC', '*',20);
        $projects = array(); // 保存提交到客户端的信息
        // 提取用户在每个项目的报名信息
        $ChealthEnterModel = D('Chealth/ChealthEnter');
        foreach ($list as $k => $v) {
            $enterInfo = $ChealthEnterModel->where(array('aid' => $v['id'], 'uid' => $this->uid))->find();
            //非女性不显示妇科体检
            if ($v['type'] == 2 && $this->user['sex'] != 0) {
                continue;
            }
            // 根据用户报名信息修改相应变量
            $status = 0;
            $status_text = '未报名';
            $chealth_time = '';
            $allow_edit = 0;
            $allow_edit_info = '';
            $allow_enter = 0;
            $file1 = '';
            $file2 = '';
            if (!empty($enterInfo)) {
                $status = (int)$enterInfo['status'];
                $status_text = $this->status_maps[$status];
                if($v['type'] == 2){
                    $chealth_time = date("Y-m-d", $enterInfo['chealth_time']);
                    if(date("H", $enterInfo['chealth_time']) == 12){
                        $chealth_time .= ' 下午';
                    }else{
                        $chealth_time .= ' 上午';
                    }
                }else{
                    $chealth_time = date("Y-m-d", $enterInfo['chealth_time']);
                }
                //检查是否可以编辑
                $allow_edit = $this->check_allow_edit($enterInfo);
                $allow_edit_info = $this->allow_edit_info;
                $file1 = $enterInfo['file1'] ?
                    U('api/download', array('id' => $enterInfo['id'], 'fid' => $enterInfo['file1'], 'token' => I('token')), true, true) : '';
                $file2 = $enterInfo['file2'] ?
                    U('api/download', array('id' => $enterInfo['id'], 'fid' => $enterInfo['file2'], 'token' => I('token')), true, true) : '';
            }
            // 组装前端文字展示
            if ($status == 0) {
                if (($v['reserve_start_time'] <= NOW_TIME_FORMAT) and empty($status) and ($v['reserve_end_time'] >= NOW_TIME_FORMAT)) {
                    $allow_enter = 1;
                    $footer_title = '点击报名';
                    $footer_link = '/enter?aid=' . $v['id'];
                } else {
                    $footer_title = '不在预约时间';
                    $footer_link = '';
                }
            } elseif ($status == 1) {
                if ($allow_edit == 1) {
                    $footer_title = '修改预约时间(可修改' . (C('LIMIT_UPDATE_NUM') - $enterInfo['update_num']) . '次)';
                    $footer_link = '/editenter?aid=' . $v['id'];
                } else {
                    $footer_title = $allow_edit_info;
                    $footer_link = '';
                }
            } else {
                $footer_title = '';
                $footer_link = '';
            }
            // 组装返回数据格式
            $projects[] = array(
                'name' => $v['name'],
                'reserve_time' => time_format($v['reserve_start_time'], 'Y-m-d') . '至' . time_format($v['reserve_end_time'], 'Y-m-d'),
                'check_time' => time_format($v['check_start_time'], 'Y-m-d') . '至' . time_format($v['check_end_time'], 'Y-m-d'),
                'status' => $status, # 0 未报名, 1 已报名, 2 已查体
                'status_text' => $status_text,
                'chealth_time' => $chealth_time,
                'allow_enter' => $allow_enter, # 0 不在预约时间, 1 可以报名
                'allow_edit' => $allow_edit,
                'allow_edit_info' => $allow_edit_info,
                'allow_edit_num' => C('LIMIT_UPDATE_NUM') - $enterInfo['update_num'],
                'footer_title' => $footer_title,
                'footer_link' => $footer_link,
                'file1' => $file1,
                'file2' => $file2
            );
        }
        $this->success(array('projects'=>$projects, 'totalCount'=>$totalCount));
    }

    /**
     * 报名
     */
    public function enter(){
        //检查用户状态,status为5时不能报名
        if($this->user['status'] == 5){
            $this->error('无法报名', '/home');
        }
        $aid = I('aid', '', 'intval');
        if(empty($aid)){
            $this->error('参数错误!', '/home');
        }
        $ChealthEnterModel = D('Chealth/ChealthEnter');
        //检查是否已经报名
        $enterInfo = $ChealthEnterModel->where(array('uid'=>$this->uid,'aid'=>$aid))->find();
        if(!empty($enterInfo)){
            $this->error('您已报名过,请勿重复报名!', '/home');
        }
        //获取预约报名项目信息
        $chealthTimeInfo = D('Chealth/ChealthTime')->getInfoById($aid);
        if(empty($chealthTimeInfo)){
            $this->error('暂无预约项目', '/home');
        }
        if(IS_POST){
            if($chealthTimeInfo['type'] == 2 && $_POST['dd'] == 1){
                $_POST['chealth_time'] += 43200;
            }
            $_POST['uid'] = $this->uid;
            $_POST['unit'] = $chealthTimeInfo['unit'];
            $_POST['name'] = $this->user['real_name'];
            $_POST['sign'] = $this->user['username'];
            $_POST['sex'] = $this->user['sex'];
            $_POST['card'] = $this->user['card'];
            $_POST['birthdate'] = strtotime($this->user['birthdate']);
            $result = $ChealthEnterModel->updateEnter();
            if (!$result) {
                $this->error($ChealthEnterModel->getError());
            }
            //清空缓存
            S('enterList_'.$chealthTimeInfo['id'], NULL);
            //更新用户部门信息和手机号信息
            $userdata = array(
                'mobile' => $_POST['mobile'],
                'department_id' => $_POST['department_id']
            );
            M('UcenterMember')->where(array('id'=>$this->uid))->save($userdata);
            //返回成功信息
            $this->success('预约成功', U('index'));
        }else{
            //获取部门信息
            $lists = D('ChealthDepartment')->select();
            unset($lists[0]);
            $department_lists = array();
            foreach ($lists as $key => $value) {
                $department_lists[] = array(
                    'key' => $value['id'],
                    'value' => $value['name']
                );
            }
            //处理不可查体时间
            $enterList = S('enterList_'.$chealthTimeInfo['id']);
            if(empty($enterList)){
                if($chealthTimeInfo['type'] == 1){
                    $enterList = $this->getEnterList($chealthTimeInfo);
                }else{
                    $enterList = $this->getEnterListFu($chealthTimeInfo);
                }
                //缓存可报名时间和已报名人数
                S('enterList_'.$chealthTimeInfo['id'], $enterList);
            }
            $chealthTimeInfo['enterList'] = $enterList;
            //处理查体项目
            $optionalItem_lists = array();
            if(!empty($chealthTimeInfo['chealth_project'])){
                $len = count($chealthTimeInfo['chealth_project']);
                for($i = 0; $i < $len; $i += 2){
                    $optionalItem_lists[] = array(
                        'key' => $chealthTimeInfo['chealth_project'][$i],
                        'value' => $chealthTimeInfo['chealth_project'][$i] . ' 费用: ' . $chealthTimeInfo['chealth_project'][$i+1]
                    );
                }
            }
            // 配置日历的信息
            $render_month = array();
            $time2count = array();
            foreach ($chealthTimeInfo['enterList'] as $k => $v) {
                $ymdkey = date('Y-m-d', $v['time']);
                if(!in_array($ymdkey, $render_month)){
                    $render_month[] = $ymdkey;    
                }
                if($chealthTimeInfo['type'] == 1){
                    $time2count[$ymdkey] = $v['count'];    
                }else{
                    $time2count[$ymdkey][date('H', $v['time'])] = $v['count'];
                }
                
            }
            $calendar = array(
                'start_date' => $render_month[0],
                'end_date' => $render_month[count($render_month)-1],
                'render_month' => $render_month,
                'time2count' => $time2count,
                'single_day_limit' => $chealthTimeInfo['single_day_limit'],
                'allow_time' => strtotime('+ '.C('CHEALTH_UPDATE_LIMIT_DAY').' day')
            );
            //返回的信息
            $result = array(
                'aid' => $aid,
                'real_name' => $this->user['real_name'],
                'birthdate' => $this->user['birthdate'],
                'mobile' => $this->user['mobile'],
                'department' => $this->user['department_id'],
                'department_lists' => $department_lists,
                'optionalItem' => '',
                'optionalItem_lists' => $optionalItem_lists,
                'calendar' => $calendar,
                'type' => $chealthTimeInfo['type']
            );
            $this->success($result);
        }
    }

    public function getEmail() {
        $this->success($this->user['email']);
    }

    /**
     * 修改报名
     */
    public function editEnter(){
        $aid = I('aid', '', 'intval');
        if(empty($aid)){
            $this->error('参数错误!', '/home');
        }
        $this->assign('aid', $aid);
        $model = D('Chealth/ChealthEnter');
        //检查是否已经报名
        $chealthEnterInfo = $model->where(array('uid'=>$this->uid,'aid'=>$aid))->find();
        if(empty($chealthEnterInfo)){
            $this->error('您未报名!', '/home');
        }
        if($chealthEnterInfo['update_num'] >= C('LIMIT_UPDATE_NUM')){
            $this->error('修改次数已使用完,无法修改,请联系管理员', '/home');
        }
        $allow_edit = $this->check_allow_edit($chealthEnterInfo);
        // TODO 正式服去掉注释
        if($allow_edit == 0){
            $this->error($this->allow_edit_info, '/home');
        }
        //获取预约报名项目信息
        $chealthTimeInfo = D('Chealth/ChealthTime')->getInfoById($aid);
        if(empty($chealthTimeInfo)){
            $this->error('暂无预约项目', U('index'));
        }
        //获取用户信息
        $user = M('UcenterMember')->find($this->uid);
        if(IS_POST){
            if($chealthTimeInfo['type'] == 2 && $_POST['dd'] == 1){
                $_POST['chealth_time'] += 43200;
            }
            $_POST['uid'] = $this->uid;
            //添加一次修改次数
            $_POST['update_num'] = $chealthEnterInfo['update_num'] + 1;
            $result = $model->updateEnter();
            if (!$result) {
                $this->error($model->getError());
            }
            S('enterList_'.$chealthTimeInfo['id'], NULL);
            //返回成功信息
            $this->success('修改预约成功', U('index'));
        }else{
            //获取部门信息
            $lists = D('ChealthDepartment')->select();
            unset($lists[0]);
            $department_lists = array();
            foreach ($lists as $key => $value) {
                $department_lists[] = array(
                    'key' => $value['id'],
                    'value' => $value['name']
                );
            }
            //获取预约报名项目信息
            $chealthTimeInfo = D('Chealth/ChealthTime')->getInfoById($aid);
            if(empty($chealthTimeInfo)){
                $this->error('暂无预约项目', U('index'));
            }
            //处理不可查体时间
            $enterList = S('enterList_'.$chealthTimeInfo['id']);
            if(empty($enterList)){
                if($chealthTimeInfo['type'] == 1){
                    $enterList = $this->getEnterList($chealthTimeInfo);
                }else{
                    $enterList = $this->getEnterListFu($chealthTimeInfo);
                }
                //缓存可报名时间和已报名人数
                S('enterList_'.$chealthTimeInfo['id'], $enterList);
            }
            $chealthTimeInfo['enterList'] = $enterList;
            //处理查体项目
            $optionalItem_lists = array();
            if(!empty($chealthTimeInfo['chealth_project'])){
                $len = count($chealthTimeInfo['chealth_project']);
                for($i = 0; $i < $len; $i += 2){
                    $optionalItem_lists[] = array(
                        'key' => $chealthTimeInfo['chealth_project'][$i],
                        'value' => $chealthTimeInfo['chealth_project'][$i] . ' 费用: ' . $chealthTimeInfo['chealth_project'][$i+1]
                    );
                }
            }
            // 配置日历的信息
            $render_month = array();
            $time2count = array();
            foreach ($chealthTimeInfo['enterList'] as $k => $v) {
                $ymdkey = date('Y-m-d', $v['time']);
                if(!in_array($ymdkey, $render_month)){
                    $render_month[] = $ymdkey;    
                }
                if($chealthTimeInfo['type'] == 1){
                    $time2count[$ymdkey] = $v['count'];    
                }else{
                    $time2count[$ymdkey][date('H', $v['time'])] = $v['count'];
                }
                
            }
            $calendar = array(
                'start_date' => date('Y-m-d', $chealthEnterInfo['chealth_time']),
                'end_date' => $render_month[count($render_month)-1],
                'render_month' => $render_month,
                'time2count' => $time2count,
                'single_day_limit' => $chealthTimeInfo['single_day_limit'],
                'allow_time' => strtotime('+ '.C('CHEALTH_UPDATE_LIMIT_DAY').' day')
            );
            //拆分自费项目
            $optionalItem = '';
            if($chealthEnterInfo['project']){
                $optionalItem = explode(',', $chealthEnterInfo['project']);
            }
            //返回的信息
            $result = array(
                'id' => $chealthEnterInfo['id'],
                'aid' => $aid,
                'real_name' => $this->user['real_name'],
                'birthdate' => $this->user['birthdate'],
                'mobile' => $this->user['mobile'],
                'department' => $this->user['department_id'],
                'department_lists' => $department_lists,
                'optionalItem' => $optionalItem,
                'optionalItem_lists' => $optionalItem_lists,
                'calendar' => $calendar,
                'type' => $chealthTimeInfo['type']
            );
            $this->success($result);
        }
    }

    /**
     * 下载文件
     */
    public function download(){
        $id = I('id');
        $fid = I('fid');
        if(empty($id) || empty($fid)){
            $this->error('参数错误');
        }
        $Enter = D('Chelath/ChealthEnter');
        // $Member = D('Common/Member');
        // $Member->login($this->uid);
        //检查是否为普通查体报告
        $map = array(
            'id' => $id,
            'uid' => $this->uid,
            'file1' => $fid,
        );
        $res = $Enter->where($map)->find();
        if(!empty($res)){
            R('Core/File/downloadFile',array('id'=>$fid));
            exit();
        }
        unset($map['file1']);
        $map['file2'] = $fid;
        $res = $Enter->where($map)->find();
        if(!empty($res)){
            R('Core/File/downloadFile',array('id'=>$fid));
            exit();
        }
        $this->error('禁止访问!');
    }

    /**
     * 获取公告
     */
    public function notice(){
        $notices = D('Chealth/ChealthNotices')->field('title, content')->where(array('id'=>1,'status'=>1))->find();
        if(empty($notices)){
            $this->error('暂无公告');
        }else{
            $this->success($notices);
        }
    }

    /**
     * 检查是否可以编辑
     * @param $info
     * @return int 1 可以编辑, 0 不可以编辑
     */
    public function check_allow_edit($info){
        if($info['status'] != 1){
            $this->allow_edit_info = '已查体';
            return 0;
        }
        if($info['update_num'] >= C('LIMIT_UPDATE_NUM')){
            $this->allow_edit_info = '修改已次数使用完';
            return 0;
        }
        $chealth_edit_day = C('CHEALTH_EDIT_DAY');
        $chealth_edit_day_limit = C('CHEALTH_EDIT_DAY_LIMIT');
        $allow_edit_end_time = $info['chealth_time'] - $chealth_edit_day * 60 * 60 * 24;
        $allow_edit_start_time = $allow_edit_end_time - $chealth_edit_day_limit * 60 * 60 * 24;
        if(NOW_TIME_FORMAT >= $allow_edit_start_time && NOW_TIME_FORMAT <= $allow_edit_end_time){
            return 1;
        }
        $this->allow_edit_info = time_format($allow_edit_start_time, 'Y-m-d') . '至' . time_format($allow_edit_end_time, 'Y-m-d') . '可修改';
        return 0;
    }

    /**
     * 检查用户是否为自动导入没有修改密码的用户
     */
    public function defaultUser(){
        if($this->user['type'] == '4'){
            $this->error('为了您的账号安全,请修改默认密码.', '/password');
        } elseif($this->user['email_verify'] == 0 or empty($this->user['email'])){
            session('temp_login_uid', $this->uid);
            $this->error('以防忘记密码, 请设置找回密码所用的邮箱', '/activate');
        }
    }

    /**
     * 验证用户身份, 初始化用户信息
     * @return bool
     */
    public function is_login(){
        $user = apiLogin();
        if($user === false){
            return false;
        }
        $this->user = $user;
        $this->uid = $user['id'];
        return true;
    }

    private function getEnterList($ainfo){
        $day = 60 * 60 * 24;
        $etime = $ainfo['check_exclude_time'];
        $excludeList = array();
        $len = count($etime);
        for($i = 0; $i < $len; $i+=2){
            for ($j = (int)$etime[$i]; $j <= $etime[$i + 1]; $j += $day) {
                $excludeList[] = $j;
            }
        }
        $enterList = array();
        for ($i=(int)$ainfo['check_start_time']; $i <= $ainfo['check_end_time']; $i+=$day) {
            if(!in_array($i, $excludeList)){
                //获取每个可报名时间的报名人数
                $count = D('Chealth/ChealthEnter')->where(array('aid'=>$ainfo['id'],'chealth_time'=>$i))->count();
                $enterList[] = array(
                    'time' => $i,
                    'count' => $count
                );
            }
        }
        return $enterList;
    }

    private function getEnterListFu($ainfo){
        $day = 60 * 60 * 12;
        $etime = $ainfo['check_exclude_time'];
        $excludeList = array();
        $len = count($etime);
        --$day;
        for($i = 0; $i < $len; $i++){
            $excludeList[] = (int)$etime[$i];
            $excludeList[] = (int)($etime[$i] + $day);
        }
        $enterList = array();
        ++$day;
        for ($i=(int)$ainfo['check_start_time']; $i <= $ainfo['check_end_time']; $i+=$day) {
            if(!in_array($i, $excludeList)){
                //获取每个可报名时间的报名人数
                $count = D('Chealth/ChealthEnter')->where(array('aid'=>$ainfo['id'],'chealth_time'=>$i))->count();
                $enterList[] = array(
                    'time' => $i,
                    'count' => $count
                );
            }
        }
        return $enterList;
    }
}